
import createSagaMiddleware, { SagaIterator } from "redux-saga";
import { all, call, put, takeEvery } from "redux-saga/effects";
import { BudgetExhibit } from "../../interface/budgetData";
import { DataRowResult } from "../../interface/response";
import { SelectBudgetListData } from "../BudgetList/budget-list-saga";
import { ActionProps } from "../type";
import { SelectBudgetExhibitDate, UpdateBudgetDate } from "./action";
import { FetchBudgetExhibitData, UpdateTotalAmountApi } from "./api";
import { BudgetDataActionEnum } from "./type";

//查询总金额和总收入支出
function* GetBudgetExhibitDataAsync(): SagaIterator
{
    try
    {
        let fetchRecordExhibitData = yield call(FetchBudgetExhibitData);
        if (fetchRecordExhibitData)
        {
            let action: ActionProps<BudgetDataActionEnum, BudgetExhibit[]> = SelectBudgetExhibitDate(fetchRecordExhibitData);
            yield put(action);
        }
    } catch (e)
    {
        throw new Error(String(e));
    }

}
export function* SelectBudgetExhibitData() { yield takeEvery('SelectBudgetExhibitData', GetBudgetExhibitDataAsync); }

//更新总金额
function* UpdateTotalAmountSaga(action: ActionProps<string, string>): SagaIterator
{
    let updateTotalAmount: DataRowResult = yield call(UpdateTotalAmountApi, action.payload);
    let _action: ActionProps<BudgetDataActionEnum, DataRowResult> = UpdateBudgetDate(updateTotalAmount);
    yield put(_action);
}
export function* UpdateTotalAmount() { yield takeEvery('UpdateTotalAmount', UpdateTotalAmountSaga); }


export function* RootSaga()
{
    yield all([
        call(SelectBudgetExhibitData),
        call(SelectBudgetListData),
        call(UpdateTotalAmount),
    ]);
}

export const sagaMiddleWare = createSagaMiddleware();
